<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Traits\Response as ResponseTrait;

class BaseController extends Controller
{
	use ResponseTrait;
	/**
	 * get result with curl tool
	 * @param string $req_url
	 * @return string
	 */
	protected function curl_get($req_url){
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $req_url);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$ret_msg = curl_exec($ch);
		if(curl_errno($ch)) {
		    echo 'Curl error: '. curl_error($ch);
		}
		curl_close($ch);
		return $ret_msg;
	}
	
	
	/**
	 * post data to url use curl
	 * @param string $url destination url
	 * @param array $postdata
	 * @param bool $ajax
	 * @return string $res
	 */
    protected function curl_post($url, $postdata, $ajax=false, $cookie=null){
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_HEADER, false);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        if($ajax){
            curl_setopt($ch, CURLOPT_HTTPHEADER, array("X-Requested-With: XMLHttpRequest"));
        }
        if($cookie){
            curl_setopt($ch, CURLOPT_COOKIE, $cookie);
        }
        $res = curl_exec($ch);
        if(curl_errno($ch)) {
            echo 'Curl error: '. curl_error($ch);
        }
        curl_close($ch);
        return $res;
    }
	
	/**
	 * 响应成功
	 * @param string $message
	 * @return \Illuminate\Http\Response
	 */
	protected function respondWithSuccess($message = '', $data = NULL)
	{
		$output = [
			'errcode' => 0,
			'errmessage'  => $message,	
		];
		if(!empty($data)) $output['data'] = is_array($data)? $data :array();
		
		return response()->json($output);
	}
	
	/**
	 * 响应所有的validation验证错误
	 * @param  \Illuminate\Validation\Validator $validator the validator that failed to pass
	 * @return \Illuminate\Http\Response the Aizxinropriate response containing the error message
	 */
	protected function respondWithFailedValidation(\Illuminate\Validation\Validator $validator)
	{
		// 只取出一条错误信息
		return $this->respondWithErrors($validator->messages()->first(), 422);
	}
	
	/**
	 * 响应错误
	 * @param string $message
	 * @param int $code
	 * @param string $status
	 * @return Response
	 */
	protected function respondWithErrors($message = '', $status_code = 1, $data = NULL)
	{
		$output = [
				'errcode' => $status_code,
				'errmessage'  => $message,
		];
		if(!empty($data)) $output['data'] = is_array($data)? $data :array();
		
		return response()->json($output);
	}
}

